package com.ninth_group.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ninth_group.constant.PawConstants;
import com.ninth_group.dao.PawDao;
import com.ninth_group.exception.province.ProvinceNameIsValidException;
import com.ninth_group.mapper.CityMapper;
import com.ninth_group.po.City;
import com.ninth_group.service.PawService;
import com.ninth_group.utils.RedisSerializerUtil;
import com.ninth_group.vo.CityVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PawServiceImpl implements PawService {
    @Resource
    private PawDao pwDao;
    @Resource
    private RedisSerializerUtil redisUtil;
    /**
     * 根据省份名获取省会的天气信息
     * @param pName 省份名称
     * @return 省会详细天气信息
     */
    @Override
    public CityVO getPawData(String pName) throws JsonProcessingException {
        if (pName == null || pName.isEmpty())
            throw new ProvinceNameIsValidException("省份名称不能为空");

        // 获取redis缓存数据
        CityVO cityVO = redisUtil.get(
                PawConstants.PROVINCE_CAPITAL_WEATHER_INFO + pName,
                CityVO.class);

        if (cityVO != null) return cityVO;
        // 查询数据库并添加到redis中
        City city = pwDao.getPawData(pName);
        System.out.println(city);

        // 转换为Vo
        CityVO cityVo = CityMapper.INSTANCE.toVo(city);

        redisUtil.set(PawConstants.PROVINCE_CAPITAL_WEATHER_INFO + pName, cityVo,
                PawConstants.CACHE_TIME, TimeUnit.MINUTES);

        return cityVo;
    }
}
